package com.fruit.interceptor;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fruit.common.CookieUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 微信登录拦截器
 * 
 * @author Administrator
 * @version 2018.02.02 12:40
 */
@Slf4j
public class WeChatSecurityInterceptor extends HandlerInterceptorAdapter {
	@Value("${h5_domain}")
	private String h5Domain;
	@Value("${domain}")
	private String domain;
	@Value("${top_domain}")
	private String topDomain;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		log.info("登录拦截处理-----开始");
		response.setContentType("text/html;charset=UTF-8");
		String ua = ((HttpServletRequest) request).getHeader("user-agent");
		if (StringUtils.isEmpty(ua)) {
			return false;
		}
		String requestType = request.getHeader("X-Requested-With");
		String forward = request.getParameter("forward");
		String sourceChannel = request.getParameter("sourceChannel");
		String urlDomain = null;
		String goUrl = null;
		if ("0".equals(sourceChannel)) {
			urlDomain = domain;
		} else {
			urlDomain = h5Domain;
		}
		
		if (StringUtils.isEmpty(forward)) {
			goUrl = urlDomain + "/index";
		} else {
			if (forward.startsWith("http://") || forward.startsWith("https://")) {
				goUrl = forward;
			} else {
				goUrl =  urlDomain + forward;
			}
		}
		log.info("参数：forward={},sourceChannel={},urlDomain={}", forward, sourceChannel, urlDomain);
		String contextPath = request.getContextPath();
		if (StringUtils.lowerCase(ua).indexOf("micromessenger") > 0) { // 是微信浏览器 判断openid 有进关联处理，没有走隐式处理 其它浏览器则进tologin
			String openId = CookieUtil.getValue(request, "publicOpenid");
			log.info("微信浏览器----开始openid={}", openId);
			if (StringUtils.isEmpty(openId)) { //没有，走隐式授权
				String url = domain + "/wap/wechat/wxValidate/getWxJsApiCode?goUrl=" + domain + URLEncoder.encode("/wap/login/doSkip?goUrl=", "UTF-8") + goUrl;
				if (!StringUtils.equals(requestType, "XMLHttpRequest")) {
					response.sendRedirect(contextPath + url);
				}
				return false;
			} else {
				String url = "/wap/login/doSkip?goUrl=" + goUrl;
				response.sendRedirect(contextPath + url);
				CookieUtil.setCookie(response, "publicOpenid", "" + openId, 30, "/", topDomain);
				return false;
			}
		} else {
			request.setAttribute("forward", goUrl);
			return true;
		}
	}
}
